package pers.yurwisher.rubick.oauth2.common;

import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import lombok.Data;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * 定制化返回token
 *
 * @author yq 2021年4月18日 23:25:12
 */
@Data
public class CustomOAuth2AccessToken implements Serializable, OAuth2AccessToken {

    private static final long serialVersionUID = -4676334755617125062L;

    private String token;

    private Date expiration;

    private Set<String> scope;

    private Map<String, Object> additionalInformation;

    private String tokenType;

    private OAuth2RefreshToken refreshToken;

    public CustomOAuth2AccessToken(OAuth2AccessToken accessToken) {
        this.token = accessToken.getValue();
        this.additionalInformation = accessToken.getAdditionalInformation();
        this.expiration = accessToken.getExpiration();
        this.refreshToken = accessToken.getRefreshToken();
        this.scope = accessToken.getScope();
        this.tokenType = accessToken.getTokenType();
    }

    public CustomOAuth2AccessToken() {
    }

    @Override
    @JSONField(serialize = false, deserialize = false)
    public Map<String, Object> getAdditionalInformation() {
        return additionalInformation;
    }

    @Override
    public Set<String> getScope() {
        return scope;
    }

    @Override
    @JSONField(serializeUsing = ToStringSerializer.class)
    public OAuth2RefreshToken getRefreshToken() {
        return refreshToken;
    }

    @Override
    public String getTokenType() {
        return tokenType;
    }

    @Override
    @JSONField(serialize = false, deserialize = false)
    public boolean isExpired() {
        Date expiration = this.getExpiration();
        return expiration != null && expiration.before(new Date());
    }

    @Override
    @JSONField(name = "expire")
    public int getExpiresIn() {
        Date expiration = this.expiration;
        return expiration != null ? Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue() : 0;
    }

    @Override
    public Date getExpiration() {
        return expiration;
    }

    @Override
    @JSONField(serialize = false, deserialize = false)
    public String getValue() {
        return token;
    }

    /**
     * 反序列化时 特殊转化
     *
     * @param refreshToken redis内为字符串
     */
    public void setRefreshToken(String refreshToken) {
        this.refreshToken = new DefaultOAuth2RefreshToken(refreshToken);
    }

}
